#!/bin/bash
# 用法：./slab_cleaner.sh [阈值百分比]

# 配置参数
THRESHOLD=${1:-80}  # 可选参数，默认80%阈值
LOG_FILE="/var/log/slab_cleaner.log"  # 日志文件

# 内存计算函数
get_memory_stats() {
    echo "┌──────────────────────────┬───────────────┐"
    grep -E 'MemTotal|Slab|SReclaimable|SUnreclaim' /proc/meminfo | awk '{printf "│ %-24s │ %7s KB │\n", $1, $2}'
    echo "└──────────────────────────┴───────────────┘"
}

# 记录开始时间
start_time=$(date +%s)
echo "===============================" | tee -a "$LOG_FILE"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] 开始Slab内存清理" | tee -a "$LOG_FILE"

# 获取初始内存状态
INIT_STATS=$(get_memory_stats)
total_mem=$(grep MemTotal /proc/meminfo | awk '{print $2}')
slab_mem=$(grep Slab /proc/meminfo | awk '{print $2}')
reclaimable=$(grep SReclaimable /proc/meminfo | awk '{print $2}')

# 计算使用率
usage_percent=$((slab_mem * 100 / total_mem))

# 输出初始状态
echo -e "\n初始内存状态：" | tee -a "$LOG_FILE"
echo "$INIT_STATS" | tee -a "$LOG_FILE"
echo "├ Slab使用率: ${usage_percent}% (阈值: ${THRESHOLD}%)" | tee -a "$LOG_FILE"
echo "├ 可回收Slab: ${reclaimable} KB" | tee -a "$LOG_FILE"

# 检查阈值条件
if [[ $usage_percent -lt $THRESHOLD ]]; then
    echo "├ 状态: 低于阈值，无需操作" | tee -a "$LOG_FILE"
    echo "└ 操作已跳过" | tee -a "$LOG_FILE"
    exit 0
fi

# 执行缓存释放
echo "├ 状态: 超过阈值，执行释放..." | tee -a "$LOG_FILE"
sync  # 确保数据写入磁盘
echo 2 > /proc/sys/vm/drop_caches 2>/dev/null

# 获取释放后状态
sleep 2
FINAL_STATS=$(get_memory_stats)
new_slab_mem=$(grep Slab /proc/meminfo | awk '{print $2}')
reclaimed=$((slab_mem - new_slab_mem))

# 计算耗时
end_time=$(date +%s)
duration=$((end_time - start_time))

# 输出最终报告
echo -e "\n内存清理完成：" | tee -a "$LOG_FILE"
echo "$FINAL_STATS" | tee -a "$LOG_FILE"
echo "├ 回收内存: ${reclaimed} KB" | tee -a "$LOG_FILE"
echo "├ 新Slab使用率: $((new_slab_mem * 100 / total_mem))%" | tee -a "$LOG_FILE"
echo "└ 耗时: ${duration} 秒" | tee -a "$LOG_FILE"